﻿using System;
using System.Text;
using System.Xml.Xsl;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace tomvangaever.library.XSLT
{
    public static class XsltHelper
    {
        public static string ApplyXSLTransformation(string xmlstring, string xsltstring)
        {
            string strHtml;
            
            // Validate input xml
            if (string.IsNullOrEmpty(xmlstring)) throw new ArgumentException("xmlstring cannot be null or empty");
            if (string.IsNullOrEmpty(xsltstring)) throw new ArgumentException("xsltstring cannot be null or empty");

            // Clear formatting
           // xsltstring = string.Join(" ", Regex.Split(xsltstring, @"(?:\r\n|\n|\r)"));
            //xmlstring = string.Join(" ", Regex.Split(xmlstring, @"(?:\r\n|\n|\r)"));

            // Read the strings into xml
            XmlReader xmlreader = XmlReader.Create(new StringReader(xmlstring));
            XmlReader xslreader = XmlReader.Create(new StringReader(xsltstring));
            
            //  Transform the xml by using the provided xsl
            XslCompiledTransform x = new XslCompiledTransform();
            XPathDocument doc = new XPathDocument(xmlreader);
            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(xslreader, new XsltSettings(false, true), new XmlUrlResolver());
            
            // Write the transformed html into a string
            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, Encoding.ASCII);
            StreamReader rd = new StreamReader(ms);
            xslt.Transform(doc, writer);
            ms.Position = 0;
            strHtml = rd.ReadToEnd();
            rd.Close();
            ms.Close();

            // Return the value
            return strHtml;
        }
    }
}
